package cn.gmph.framework.config.beans;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

import cn.gmph.common.constant.Constants;

public class ExceptionConfig {
    Logger logger = Logger.getLogger(ExceptionConfig.class);

    @Bean(name = "exceptionHandler")
    public MyExceptionHandler getMyExceptionHandler() {
        MyExceptionHandler exceptionHandle = new MyExceptionHandler();
        return exceptionHandle;
    }

    class MyExceptionHandler implements HandlerExceptionResolver {

        public ModelAndView resolveException(HttpServletRequest request,
                                             HttpServletResponse response, Object handler,
                                             Exception ex) {
            logger.error("系统异常", ex);
            HandlerMethod hand = (HandlerMethod) handler;
            Method method = hand.getMethod();
            ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method,
                ResponseBody.class);
            if (responseBodyAnn != null) {
                return setJsonView(response, ex);
            }
            return new ModelAndView();
        }

        private void setJsonData(HttpServletResponse response, Exception ex) {
            ModelAndView mv = new ModelAndView();
            /*  使用response返回    */
            response.setStatus(HttpStatus.OK.value()); //设置状态码  
            response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType  
            response.setCharacterEncoding("UTF-8"); //避免乱码  
            response.setHeader("Cache-Control", "no-cache, must-revalidate");

            //Result<> result = new Result();
            //result.setError();
            //result.setError("系统错误");
            //response.getWriter().write(result.toAppJson());

        }

        private ModelAndView setJsonView(HttpServletResponse response, Exception ex) {
            ModelAndView mv = new ModelAndView();
            /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */
            FastJsonJsonView jsonView = new FastJsonJsonView(); 
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("result", false);
            attributes.put("resultCode", Constants.ErrorCodeEnum.SYS_ERROR.getCode());
            attributes.put("data", null);
            attributes.put("resultMessage", Constants.ErrorCodeEnum.SYS_ERROR.getMessage());
            jsonView.setAttributesMap(attributes);
            mv.setView(jsonView);
            return mv;
        }
    }

}
